package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.common.constants.JwtConstants.*;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void login(String username, String password, HttpServletResponse response) {
    //根据用户名和密码查询用户
        UserDTO userDTO = null;
        try {
            userDTO=userClient.queryUserByUsernameAndPassword(username,password);
        } catch (FeignException e) {
            if (e.status() == 400) {
                //用户名或密码错误
                throw new LyException(e.status(), e.contentUTF8());
            }
            throw new LyException(500, "验证用户失败", e);
        }
           //对查询结果判断
            if (userDTO == null){
               //用户不存在，用户名或密码错误
            throw  new LyException(401,"用户名或密码错误");
            }
            //生成jwt
            String jwt = jwtUtils.createJwt(UserDetails.of(userDTO.getId(), userDTO.getUsername()));
            //写入cookies
            writeJwt2Cookie(response, jwt);
        }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if (jwt==null){
            //用户未登陆
            return;
        }
        try {
            //解析jwt
            Payload payload = jwtUtils.parseJwt(jwt);
            //删除redis
            Long userId = payload.getUserDetail().getId();
            jwtUtils.deleteJwt(userId);

        } catch (Exception e) {
          //解析失败，有可能是未登录，放弃退出
        }
        //删除cookies
        CookieUtils.deleteCookie(COOKIE_NAME,DOMAIN,response);
    }


    private void writeJwt2Cookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME,jwt);
        cookie.setPath(COOKIE_PATH);
        cookie.setHttpOnly(true);
        cookie.setDomain(DOMAIN);
        response.addCookie(cookie);
    }
}
